package com.android.lib.download.utils

import android.os.Environment
import java.security.MessageDigest

object Utils {

    /** md5加密 */
    fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length -2))
        }
        return hex.toString()
    }

    fun getUrlFileName(url: String?): String {
        url ?: return "unknownfile_${System.currentTimeMillis()}"
        var filename: String? = null
        val strings = url.split("/").toTypedArray()
        for (string in strings) {
            if (string.contains("?")) {
                val endIndex = string.indexOf("?")
                if (endIndex != -1) {
                    filename = string.substring(0, endIndex)
                    return filename
                }
            }
        }
        if (strings.isNotEmpty()) {
            filename = strings[strings.size - 1]
        }
        filename ?: return "unknownfile_${System.currentTimeMillis()}"
        return filename
    }

    fun getRooDir(): String? {
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
           return ContextHolder.application.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
        }
        return ContextHolder.application.filesDir.absolutePath
    }


}